﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

using MicroCenter.Models;

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace MicroCenter.Services
{
    [Injection(ServiceLifetime.Singleton), JobService]
    public class LogService
    {
        private readonly string path;

        public LogService(IWebHostEnvironment hostingEnvironment)
        {
            path = Path.Combine(hostingEnvironment.WebRootPath, "logs");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        public List<FileModel> LookLogs(string serviceName)
        {
            string root = Path.Combine(path, serviceName);
            if (!Directory.Exists(root))
                return new List<FileModel>();
            var directoryInfo = new DirectoryInfo(root);
            return directoryInfo.GetFiles().Select(a => new FileModel
            {
                Name = a.Name,
                Length = a.Length,
                LastWriteTime = a.LastWriteTime,
                CreationTime = a.CreationTime,
            }).OrderByDescending(a => a.CreationTime).ToList();
        }
        public string Read(string serviceName, string name)
        {
            string log = Path.Combine(path, serviceName, name);
            if (!File.Exists(log))
                return null;
            return File.ReadAllText(log);
        }

        public void Write(string sb, string name)
        {
            string dp = Path.Combine(path, name);
            lock (this)
            {
                string text = sb + "\n\r";
                if (!Directory.Exists(dp))
                {
                    Directory.CreateDirectory(dp);
                }
                string log = Path.Combine(dp, $"{ DateTime.Now:yyyy-MM-dd}.log");
                File.AppendAllText(log, text);
            }
        }

        public void ClearCurrentDay(string name)
        {
            string log = Path.Combine(path, name, $"{ DateTime.Now:yyyy-MM-dd}.log");
            if (File.Exists(log))
                File.Delete(log);
        }

        [Corn("0 0 0 * * ? *")]
        public void Clear()
        {
            DateTime det = DateTime.Now.AddDays(-7);
            if (DateTime.Now.Hour <= 1)
            {
                foreach (var item in Directory.GetDirectories(path))
                {
                    foreach (var a in Directory.GetFiles(item))
                    {
                        if (File.GetCreationTime(a) < det)
                        {
                            File.Delete(a);
                        }
                    }
                }
            }
        }
    }
}
